package com.example.ribboncodeconsumer.controller;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class ConsumerController {
    // Ribbon 提供的负载均衡客户端
    @Resource
    private LoadBalancerClient loadBalancerClient;

    // Spring 提供进行 Restful 请求对象
    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer")
    public String consumer(@RequestParam String name) {
        // 根据 Nacos 的服务 id 获取服务实例
        ServiceInstance serviceInstance = loadBalancerClient.choose("springcloud-nacos-provider");
        // 获取服务实例中的 ip
        String ip = serviceInstance.getHost();
        // 获取服务实例中的端口号
        int port = serviceInstance.getPort();
        // 使用 restTemplate 请求并获取结果
        String result = restTemplate.getForObject("http://" + ip + ":" + port + "/call/" + name,
                String.class);
        return result;
    }
}
